import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Permission } from '../database/entities/permission.entity';
import { CreatePermissionDto, UpdatePermissionDto, QueryPermissionsDto } from './dto/permissions.dto';

@Injectable()
export class PermissionsService {
  constructor(
    @InjectRepository(Permission)
    private permissionsRepository: Repository<Permission>,
  ) {}

  async create(createPermissionDto: CreatePermissionDto): Promise<Permission> {
    const permission = this.permissionsRepository.create(createPermissionDto);
    return this.permissionsRepository.save(permission);
  }

  async findAll(query: QueryPermissionsDto) {
    const { 
      page = 1, 
      pageSize = 10, 
      keyword, 
      name,
      code,
      type, 
      resource,
      status,
      createTimeStart,
      createTimeEnd,
      sortBy = 'sort',
      sortOrder = 'DESC'
    } = query;
    
    const queryBuilder = this.permissionsRepository.createQueryBuilder('permission');

    // 关键词搜索（模糊匹配）
    if (keyword) {
      queryBuilder.andWhere(
        '(permission.name LIKE :keyword OR permission.code LIKE :keyword OR permission.description LIKE :keyword)',
        { keyword: `%${keyword}%` }
      );
    }

    // 权限名精确搜索
    if (name) {
      queryBuilder.andWhere('permission.name = :name', { name });
    }

    // 权限代码精确搜索
    if (code) {
      queryBuilder.andWhere('permission.code = :code', { code });
    }

    // 权限类型筛选
    if (type) {
      queryBuilder.andWhere('permission.type = :type', { type });
    }

    // 资源路径搜索（模糊匹配）
    if (resource) {
      queryBuilder.andWhere('permission.resource LIKE :resource', { 
        resource: `%${resource}%` 
      });
    }

    // 状态筛选
    if (status !== undefined) {
      queryBuilder.andWhere('permission.status = :status', { status });
    }

    // 创建时间范围搜索
    if (createTimeStart) {
      queryBuilder.andWhere('DATE(permission.createTime) >= :createTimeStart', { 
        createTimeStart 
      });
    }

    if (createTimeEnd) {
      queryBuilder.andWhere('DATE(permission.createTime) <= :createTimeEnd', { 
        createTimeEnd 
      });
    }

    // 排序
    const allowedSortFields = ['sort', 'createTime', 'updateTime', 'name', 'type'];
    const orderBy = allowedSortFields.includes(sortBy) ? sortBy : 'sort';
    const orderDirection = sortOrder === 'ASC' ? 'ASC' : 'DESC';
    
    const [list, total] = await queryBuilder
      .orderBy(`permission.${orderBy}`, orderDirection)
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();

    return {
      list,
      total,
      page,
      pageSize,
    };
  }

  async findById(id: number): Promise<Permission> {
    const permission = await this.permissionsRepository.findOne({
      where: { id },
    });
    
    if (!permission) {
      throw new NotFoundException('权限不存在');
    }
    
    return permission;
  }

  async update(id: number, updatePermissionDto: UpdatePermissionDto): Promise<Permission> {
    const permission = await this.findById(id);
    Object.assign(permission, updatePermissionDto);
    return this.permissionsRepository.save(permission);
  }

  async remove(id: number): Promise<void> {
    const permission = await this.findById(id);
    await this.permissionsRepository.remove(permission);
  }
}